import Vue from 'vue';
import { Component, Prop } from 'vue-property-decorator';
import { formatBigNumber } from '@/modules/utils/common-utils';
import http from '@/modules/http/index';
import CommentItem from './comment-item/index.vue';
import ModalAlert from '@liepin/mp-modal-wx/src/index.vue';
import vPopup from '@liepin/cnpm-uni-popup-wx';
import TStatus from '@/components/t-status/index.vue';
import TLoading from '@/components/t-loading/index.vue';
import { getLoginStatus, getCurrentPath } from '@/modules/utils';

@Component({
  components: { CommentItem, ModalAlert, vPopup, TStatus, TLoading }
})
export default class TComment extends Vue {
  /* 文章id */
  @Prop({ default: 0 })
  private articleId: number;

  @Prop({ default: false })
  private isLike: boolean = false;

  @Prop({ default: '' })
  private shareButtonType: string;

  @Prop()
  private likeCount: number;

  @Prop({ default: {} })
  private attachedParams: any;

  private sortType: number = 1;

  private commentTotal: number = 0;

  private commentList = [];

  private inputHasFocus: boolean = false;

  private inputContent: string = '';

  private isLoading: boolean = false;

  private modalVisible: boolean = false;

  private operateCommentIndex: number;

  private popupVisible: boolean = false;

  // eslint-disable-next-line unicorn/no-null
  private replyItem: any = null;

  private inputPlaceholder = '写评论';

  private replyList: any = [];

  private intoViewId: string = '';

  private replyModalVisible: boolean = false;

  public hasMore: boolean = false;

  private lastData: any;

  private loadMoreLoading: boolean = false;

  private replyHasMore: boolean = false;

  private replyLastData: any;

  private replyLoadMoreLoading: boolean = false;

  private publishCommentLoading: boolean = false;

  formatBigNum(number) {
    return formatBigNumber(number);
  }

  sortChange(sortType) {
    this.sortType = sortType;
    this.fetchCommentListService();
  }

  created() {
    this.fetchCommentListService();
  }

  /**
   * 获取评论列表
   * @param {data} object 请求数据
   * @param {lastData} object 最后一条的数据
   * @return {}
   */
  fetchCommentListService(data = {}, lastData: any = {}) {
    http.request({
      url: '/wx-userc/articlecomment/listbywaterfall.json',
      data: {
        articleId: this.articleId,
        sortType: this.sortType,
        pageSize: 10,
        ...this.attachedParams,
        ...data,
        ...lastData
      },
      success: ({ data: { data, flag } }) => {
        if (flag) {
          this.commentTotal = data.total;
          this.commentList = lastData?.lastId
            ? [...this.commentList, ...data.data]
            : [...data.data];
          this.hasMore = data.hasMoreFlag;
          if (data.hasMoreFlag && data.data.length > 0) {
            const _lastData = data.data[data.data.length - 1];
            this.lastData = {
              lastLikeCount: _lastData.likeCount,
              lastId: _lastData.id
            };
          }
        }
      },
      complete: () => {
        this.loadMoreLoading = false;
      }
    });
  }

  /**
   * 提供给外部使用的方法，可以触发是否加载下一页
   * @param {}
   * @return {}
   */
  loadMore() {
    if (this.loadMoreLoading) return;
    this.loadMoreLoading = true;
    this.fetchCommentListService({}, this.lastData);
  }

  changeInputFocus(status) {
    this.inputHasFocus = status;
  }

  onGoodClick() {
    this.$emit('onGoodClick');
  }

  onDiscusClick() {
    this.$emit('onDiscusClick', 'custom-comment-component');
  }

  /**
   * 发布动作，根据状态的不同，分发到不同的Service
   * @param {}
   * @return {}
   */
  publishAction() {
    // 无登录状态，跳转
    if (!getLoginStatus()) {
      uni.navigateTo({
        url: `/pages/login/index?backUrl=${encodeURIComponent(getCurrentPath())}`
      });
      return;
    }

    if (!this.inputContent) return;
    if (this.publishCommentLoading) return;
    this.publishCommentLoading = true;
    if (this.popupVisible && this.replyItem) {
      // 评论
      if (this.replyItem.toId) {
        // 回复某个人
        this.replyCommentService({
          articleCommentId: this.replyItem.id,
          toId: this.replyItem.toId,
          content: this.inputContent
        });
      } else {
        // 普通回复
        this.replyCommentService({
          articleCommentId: this.replyItem.id,
          content: this.inputContent
        });
      }
    } else {
      // 普通评论
      this.publishCommentService();
    }
  }

  /**
   * 创建评论-提交到服务器
   * @param {}
   * @return {}
   */
  publishCommentService() {
    http.request({
      url: '/wx-userc/articlecomment/createarticlecomment.json',
      data: {
        ...this.attachedParams,
        articleId: this.articleId,
        content: this.inputContent
      },
      success: ({ data: { data, flag } }) => {
        if (flag) {
          this.inputContent = '';
          this.commentTotal = this.commentTotal + 1;
          this.commentList = [
            {
              ...data,
              isNew: true
            },
            ...this.commentList
          ];
          this.$emit('onCommentSuccess', 'custom-comment-component');
        }
      },
      complete: () => {
        this.publishCommentLoading = false;
      }
    });
  }

  /**
   * 创建评论回复-提交到服务器
   * @param {data} object 提交到服务器的数据
   * @return {}
   */
  replyCommentService(data) {
    http.request({
      url: '/wx-userc/articlecommentreply/createarticlecommentreply.json',
      data: {
        ...this.attachedParams,
        ...data
      },
      success: ({ data: { data, flag } }) => {
        if (flag) {
          this.inputContent = '';
          // eslint-disable-next-line unicorn/no-null
          this.replyItem.toId = null;
          this.inputPlaceholder = '写评论';
          this.commentTotal = this.commentTotal + 1;
          this.replyItem.commentReplyCount = this.replyItem.commentReplyCount + 1;
          this.intoViewId = 'comment-drawer-header';
          this.replyList = [
            {
              ...data,
              isNew: true
            },
            ...this.replyList
          ];
          setTimeout(() => {
            this.intoViewId = '';
          }, 500);
        }
      },
      complete: () => {
        this.publishCommentLoading = false;
      }
    });
  }

  commentContentChange(event) {
    this.inputContent = event.detail.value;
  }

  /**
   * 底层评论点赞
   * @param {comment} Object 评论的服务器数据
   * @param {index} number 评论的索引
   * @return {}
   */
  onCommentGoodClick(comment, index) {
    // 无登录状态，跳转
    if (!getLoginStatus()) {
      uni.navigateTo({
        url: `/pages/login/index?backUrl=${encodeURIComponent(getCurrentPath())}`
      });
      return;
    }
    if (this.isLoading) return;
    this.isLoading = true;
    const _isGood = comment.likedFlag;
    this.commentList[index].likedFlag = !_isGood;
    const _serviceUrl = _isGood
      ? '/wx-userc/articlecomment/deletearticlecommentlike.json'
      : '/wx-userc/articlecomment/createarticlecommentlike.json';
    http.request({
      url: _serviceUrl,
      data: {
        ...this.attachedParams,
        id: comment.id
      },
      success: ({ data: { flag } }) => {
        if (flag) {
          this.commentList[index].likeCount = _isGood
            ? this.commentList[index].likeCount - 1
            : this.commentList[index].likeCount + 1;
        } else {
          // 恢复
          this.commentList[index].likedFlag = _isGood;
        }
        this.isLoading = false;
      },
      fail: () => {
        this.commentList[index].likedFlag = _isGood;
        this.isLoading = false;
      }
    });
  }

  /**
   * 弹层头部评论点赞
   * @param {}
   * @return {}
   */
  onCommentReplyGoodClick() {
    // 无登录状态，跳转
    if (!getLoginStatus()) {
      uni.navigateTo({
        url: `/pages/login/index?backUrl=${encodeURIComponent(getCurrentPath())}`
      });
      return;
    }
    if (this.isLoading) return;
    this.isLoading = true;
    const _isGood = this.replyItem.likedFlag;
    this.commentList[this.operateCommentIndex].likedFlag = !_isGood;
    this.replyItem.likedFlag = !_isGood;
    const _serviceUrl = _isGood
      ? '/wx-userc/articlecomment/deletearticlecommentlike.json'
      : '/wx-userc/articlecomment/createarticlecommentlike.json';
    http.request({
      url: _serviceUrl,
      data: {
        ...this.attachedParams,
        id: this.replyItem.id
      },
      success: ({ data: { flag } }) => {
        if (flag) {
          this.commentList[this.operateCommentIndex].likeCount = _isGood
            ? this.commentList[this.operateCommentIndex].likeCount - 1
            : this.commentList[this.operateCommentIndex].likeCount + 1;

          this.replyItem.likeCount = _isGood
            ? this.replyItem.likeCount - 1
            : this.replyItem.likeCount + 1;
        } else {
          // 恢复
          this.commentList[this.operateCommentIndex].likedFlag = _isGood;
          this.replyItem.likedFlag = _isGood;
        }
        this.isLoading = false;
      },
      fail: () => {
        this.commentList[this.operateCommentIndex].likedFlag = _isGood;
        this.replyItem.likedFlag = _isGood;
        this.isLoading = false;
      }
    });
  }

  /**
   * 评论回复点赞
   * @param {replyListItem} Object 评论回复的所有数据
   * @param {index} number 评论回复的所在索引
   * @return {}
   */
  onCommentReplyListGoodClick(replyListItem, index) {
    if (this.isLoading) return;
    this.isLoading = true;
    const _isGood = replyListItem.likedFlag;
    this.replyList[index].likedFlag = !_isGood;
    const _serviceUrl = _isGood
      ? '/wx-userc/articlecommentreply/deletearticlecommentreplylike.json'
      : '/wx-userc/articlecommentreply/createarticlecommentreplylike.json';
    http.request({
      url: _serviceUrl,
      data: {
        ...this.attachedParams,
        id: replyListItem.id
      },
      success: ({ data: { flag } }) => {
        if (flag) {
          this.replyList[index].likeCount = _isGood
            ? this.replyList[index].likeCount - 1
            : this.replyList[index].likeCount + 1;
        } else {
          // 恢复
          this.replyList[index].likedFlag = _isGood;
        }
        this.isLoading = false;
      },
      fail: () => {
        this.replyList[index].likedFlag = _isGood;
        this.isLoading = false;
      }
    });
  }

  /**
   * 删除评论弹窗触发
   * @param {index} number 索引
   * @return {}
   */
  onDeleteComment(index) {
    // 无登录状态，跳转
    if (!getLoginStatus()) {
      uni.navigateTo({
        url: `/pages/login/index?backUrl=${encodeURIComponent(getCurrentPath())}`
      });
      return;
    }
    this.operateCommentIndex = index;
    this.modalVisible = true;
  }

  /**
   * 确认删除文章评论-底层
   * @param {}
   * @return {}
   */
  handleConfirm() {
    http.request({
      url: '/wx-userc/articlecomment/deletearticlecomment.json',
      data: {
        ...this.attachedParams,
        id: this.commentList[this.operateCommentIndex].id
      },
      success: ({ data: { flag } }) => {
        if (flag) {
          this.commentTotal =
            this.commentTotal - this.commentList[this.operateCommentIndex].commentReplyCount - 1;
          let _commentList = JSON.parse(JSON.stringify(this.commentList));
          _commentList.splice(this.operateCommentIndex, 1);
          this.commentList = [..._commentList];
          this.modalVisible = false;
        }
      }
    });
  }

  handleCancel() {
    this.modalVisible = false;
  }

  /**
   * 底层页面回复按钮事件
   * @param {comment} Object 点击的该评论数据
   * @param {index} number 点击的该评论索引
   * @return {}
   */
  onReply(comment, index) {
    uni.showLoading({ title: '加载中...' });
    /**
     * 获取单个详情
     */
    http.request({
      url: '/wx-userc/articlecomment/detail.json',
      data: {
        ...this.attachedParams,
        id: comment.id
      },
      success: ({ data: { data, flag } }) => {
        if (flag) {
          // 更新评论列表的数据
          this.commentList[index] = {
            ...data
          };
          this.replyItem = {
            ...data
          };
          this.operateCommentIndex = index;
          this.popupVisible = true;
          this.$emit('onReplyModalVisibleChange', true);
          uni.hideLoading();
        }
      }
    });
    /**
     * 获取全部回复的列表
     */
    this.fetchReplyList({
      articleCommentId: comment.id
    });
  }

  /**
   * 回复弹层关闭
   * @param {}
   * @return {}
   */
  onPopupClose() {
    this.popupVisible = false;
    this.commentList[this.operateCommentIndex].commentReplyCount = this.replyItem.commentReplyCount;
    this.$emit('onReplyModalVisibleChange', false);
    // eslint-disable-next-line unicorn/no-null
    this.replyItem = null;
    this.inputPlaceholder = '写评论';
  }

  /**
   * 获取全部回复列表
   * @param {requestParameters} Object 请求的参数
   * @return {}
   */
  fetchReplyList(requestParameters) {
    http.request({
      url: '/wx-userc/articlecommentreply/listbywaterfall.json',
      data: {
        ...this.attachedParams,
        ...requestParameters,
        pageSize: 10
      },
      success: ({ data: { data, flag } }) => {
        if (flag) {
          this.replyList = requestParameters?.lastId
            ? [...this.replyList, ...data.data]
            : [...data.data];
          this.replyHasMore = data.hasMoreFlag;
          if (data.hasMoreFlag && data.data.length > 0) {
            const _lastData = data.data[data.data.length - 1];
            this.replyLastData = {
              articleCommentId: requestParameters.articleCommentId,
              lastId: _lastData.id
            };
          }
        }
      },
      complete: () => {
        this.replyLoadMoreLoading = false;
      }
    });
  }

  scrollToLower() {
    if (!this.replyHasMore) return;
    if (this.replyLoadMoreLoading) return;
    this.replyLoadMoreLoading = true;
    this.fetchReplyList({ ...this.replyLastData });
  }

  onCommentItemReply(commentItem) {
    this.replyItem = {
      ...this.replyItem,
      toId: commentItem.id
    };
    this.inputPlaceholder = `回复@${commentItem.userName}`;
    this.inputHasFocus = true;
  }

  /**
   * 删除回复按钮点击事件
   * @param {index} number 删除索引
   * @return {}
   */
  onDeleteReply(index) {
    // 无登录状态，跳转
    if (!getLoginStatus()) {
      uni.navigateTo({
        url: `/pages/login/index?backUrl=${encodeURIComponent(getCurrentPath())}`
      });
      return;
    }
    this.operateCommentIndex = index;
    this.replyModalVisible = true;
  }

  /**
   * 取消删除回复
   * @param {}
   * @return {}
   */
  handleReplyCancel() {
    this.replyModalVisible = false;
  }

  /**
   * 确认删除评论回复
   * @param {}
   * @return {}
   */
  handleReplyConfirm() {
    http.request({
      url: '/wx-userc/articlecommentreply/deletearticlecommentreply.json',
      data: {
        ...this.attachedParams,
        id: this.replyList[this.operateCommentIndex].id
      },
      success: ({ data: { flag } }) => {
        if (flag) {
          this.commentTotal = this.commentTotal - 1;
          this.replyItem.commentReplyCount = this.replyItem.commentReplyCount - 1;
          let _replyList = JSON.parse(JSON.stringify(this.replyList));
          _replyList.splice(this.operateCommentIndex, 1);
          this.replyList = [..._replyList];
          this.replyModalVisible = false;
        }
      }
    });
  }

  /**
   * 分享按钮点击事件
   * @param {}
   * @return {}
   */
  onShareClick() {
    // 无登录状态，跳转
    if (!getLoginStatus()) {
      uni.navigateTo({
        url: `/pages/login/index?backUrl=${encodeURIComponent(getCurrentPath())}`
      });
    }
  }
}
